package com.cyj.securitydemo1.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyj.securitydemo1.dao.UsersMapper;
import com.cyj.securitydemo1.pojo.Users;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Slf4j
@Service("userDetailsService")
public class MyUserDetailService implements UserDetailsService {
    @Autowired
    UsersMapper usersMapper;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public UserDetails loadUserByUsername(String username) {
//         //判断用户名是否存在
//        if (!"mary".equals(username)) {
//            log.info("用户名不存在!");
//            throw new UsernameNotFoundException("用户名不存在！");
//        }
        QueryWrapper<Users> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Users user = usersMapper.selectOne(wrapper);
        // 判断用户名是否存在
        if (user == null) {
            log.info("用户名不存在!");
            throw new UsernameNotFoundException("用户名不存在！");
        }
        // 从数据库中获取的密码 atguigu 的密文
        String pwd = user.getPassword();

        // 第三个参数表示权限
        List<GrantedAuthority> grantedAuthorities = AuthorityUtils.commaSeparatedStringToAuthorityList("admin,ROLE_sale");
        return new User(username, pwd, grantedAuthorities);
    }
}